import {
  getTakeAwayMoneySettingById,
  getTakeAwayMoneySettingAll,
  getTakeAwayMoneySettingPageList,
  commonUpdate,
  updateTakeAwayMoneySetting,
  addTakeAwayMoneySetting,
  deleteTakeAwayMoneySetting
} from '@/services/takeAwayMoneySettingService';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Popconfirm, Space, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import UpdateModal from '@/pages/basicSetting/moneySetting/updateModal'
import { getTakeAwayGoodTypeAll } from '@/services/takeAwayGoodTypeService';

/**
 *
 * @constructor
 */
const TakeAwayMoneySettingPage: React.FC<unknown> = () => {
  const [updateData, setUpdateData] = useState<TakeAwayMoneySettingType.TakeAwayMoneySetting>();
  const [isShow, setIsShow] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  const test = async () => {
    const { Items } = await getTakeAwayGoodTypeAll({ "@relationships": "GoodList", "ShopId": 1 });
    console.log(Items);
  }

  /**
   *
   * @param
   */
  const doDelete = async (model: TakeAwayMoneySettingType.TakeAwayMoneySetting) => {
    const hide = message.loading('正在删除');
    if (!model?.Id) {
      return;
    }
    try {
      await deleteTakeAwayMoneySetting({
        id: model.Id,
      });
      message.success('操作成功');
      actionRef.current?.reload();
    } catch (e: any) {
      message.error('操作失败，' + e.message);
    } finally {
      hide();
    }
  };

  useEffect(() => {
    test();
  }, [])

  /**
   *
   */
  const columns: ProColumns<TakeAwayMoneySettingType.TakeAwayMoneySetting>[] = [

    {
      title: 'id',
      dataIndex: 'Id',
      hideInSearch: true,
    },
    {
      title: '距离范围',
      dataIndex: 'MinDistance',
      hideInSearch: true,
      renderText(text, record) {
        return record.MinDistance + ' ~ ' + record.MaxDistance + ' 公里 ';
      },
    },
    {
      title: '费用',
      dataIndex: 'Money'
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <Space split={<Divider type="vertical" />}>
          <Typography.Link
            onClick={() => {
              setIsShow(true);
              setUpdateData(record);
            }}
          >
            修改
          </Typography.Link>
          <Popconfirm
            title="您确定要删除么？"
            onConfirm={() => doDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TakeAwayMoneySettingType.TakeAwayMoneySetting>
        headerTitle="管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setIsShow(true);
              setUpdateData(undefined);
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params: any, sorter: any) => {
          const searchParams: PageInfo.PageRequest = {
            pageSize: params.pageSize,
            current: params.current
          };

          let sortQuery = "", filterQuery = "";
          // eslint-disable-next-line guard-for-in
          for (const key in sorter) {
            sortQuery += `${key}|${sorter[key]}`;
          }

          if (sortQuery != "") {
            searchParams['@sort'] = sortQuery;
          }

          for (const key in params) {
            if (key !== "pageSize" && key !== "current") {
              if (params[key] != "") {
                filterQuery += `contains(${key},${params[key]})&`;
                params[key] = '';
              }
            }
          }

          if (filterQuery != "") {
            searchParams['@filter'] = filterQuery;
          }

          searchParams['@relationships'] = "UserInfo";
          const { Items, StatusCode } = await getTakeAwayMoneySettingPageList(searchParams);
          return {
            data: Items[0]?.Records || [],
            success: StatusCode === 200,
            total: Items[0].Total,
          } as any;
        }}
        columns={columns}
      />

      {isShow ? <UpdateModal id={updateData?.Id} onCancel={() => { setIsShow(false); actionRef.current?.reload(); }} modalVisible={isShow} onSubmit={() => { setIsShow(false); actionRef.current?.reload(); }} /> : null}


    </PageContainer>
  );
};

export default TakeAwayMoneySettingPage;
